# 感知
# acvs_days 档是所有档 档的p可变 只存当时的p
# p_id  acvs_id day(一天的开始时间) count脸进来的次数 （同一个脸不计次数）
import time


class Perception:

    def __init__(self, mongo_client, redis_client):
        # self.data = {}  # camera_id  [(acvs_id, timestamp)]
        self.redis_client = redis_client
        self.mongo_client = mongo_client

    def handel_logic(self, timestamp, acvs_id, face_id):
        start_time, end_time = self.get_timestamp(time.time())
        if start_time <= timestamp < end_time:
            acvs_p_id = self.get_p_id(acvs_id)
            data = {
                "acvs_id": acvs_id,
                "p": acvs_p_id,
                "day": start_time,
            }

            self.mongo_client.up_perception(data)

    def get_p_id(self, acvs_id):
        acvs_list = self.redis_client.get_acvs_acvs(acvs_id)
        if len(acvs_list) == 0:
            acvs_p_id = acvs_id
        else:
            acvs_list.append(acvs_id)
            acvs_map = {}
            for acvs_id_one in acvs_list:
                count = self.redis_client.get_acvs_face_count(acvs_id_one)
                acvs_map[acvs_id_one] = count

            acvs_map_list = sorted(acvs_map.items(), key=lambda d: d[1], reverse=True)
            # p_id
            acvs_p_id = acvs_map_list[0][0]
        return acvs_p_id

    # 转本地时间
    def get_timestamp(self, timestamp):
        time_array = time.localtime(timestamp)
        other_style_time = time.strftime("%Y-%m-%d", time_array)  # 格式化时间 得到具体某天
        time_array = time.strptime(other_style_time, "%Y-%m-%d")  # 时间元组
        timestamp = int(time.mktime(time_array))  # 将元组转化为时间戳
        return timestamp, timestamp + 86400
